package com.anji.plus.gaea.utils;

import com.anji.plus.gaea.holder.UserContentHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.TimeZone;

/**
 * 转换日期
 * @author lr
 * @since 2021-01-12
 */
public abstract class GaeaDateUtils {
    private static Logger logger = LoggerFactory.getLogger(GaeaDateUtils.class);

    public static final String timePattern = "yyyy-MM-dd HH:mm:ss";

    private static final String yearPattern = "^2[0-9]{3}$";
    private static final String monthPattern = "^2[0-9]{3}-(0?[1-9]|1[0-2])$";
    private static final String janPattern = "(0?[13578]|1[02])-(0?[1-9]|[12][0-9]|3[01])";
    private static final String febPattern = "0?2-(0?[1-9]|[12][0-9])";
    private static final String aprPattern = "(0?[469]|11)-(0?[1-9]|[12][0-9]|30)";
    private static final String dayPattern = String.format("^2[0-9]{3}-(%s|%s|%s)$", janPattern, febPattern, aprPattern);
    private static final String hourFormat = String.format("^2[0-9]{3}-(%s|%s|%s) ([01][0-9]|2[0-3]):00:00$", febPattern, janPattern, aprPattern);
    private static final String timeFormat = String.format("^2[0-9]{3}-(%s|%s|%s) ([01][0-9]|2[0-3])(:[0-5][0-9]){2}$", febPattern, janPattern, aprPattern);

    /**
     * 日期转换为指定格式的字符串
     * @param date
     * @param pattern
     * @return
     */
    public static String toString(Date date, String pattern) {
        LocalDateTime localDateTime = toLocalDateTime(date);
        return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
    }

    /**
     * 日期转换为指定格式的字符串
     * @param localDate
     * @param pattern
     * @return
     */
    public static String toString(LocalDate localDate, String pattern) {
        return localDate.format(DateTimeFormatter.ofPattern(pattern));
    }

    /**
     * 把指定格式的字符串转换为LocalDate
     * @param dateString
     * @param pattern
     * @return
     */
    public static LocalDate fromString(String dateString, String pattern) {
        return LocalDate.parse(dateString, DateTimeFormatter.ofPattern(pattern));
    }


    /**
     * LocalDate 转换为Date
     * @param localDate
     * @return
     */
    public static Date toDate(LocalDate localDate) {
        if (localDate == null) {
            return null;
        }
        return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * localDateTime 转换为Date
     * @param localDateTime
     * @return
     */
    public static Date toDate(LocalDateTime localDateTime) {
        if (localDateTime == null) {
            return null;
        }
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * date 转换为LocalDate
     * @param date
     * @return
     */
    public static LocalDate toLocalDate(Date date) {
        if (date == null) {
            return null;
        }
        return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
    }



    /**
     * date 转换为LocalDateTime
     * @param date
     * @return
     */
    public static LocalDateTime toLocalDateTime(Date date) {
        if (date == null) {
            return null;
        }
        return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }


    /**
     * 秒转天、时、分、秒
     * @param seconds
     * @return
     */
    public static String formatFromSecond(long seconds) {
        StringBuilder builder = new StringBuilder();

        long hourSeconds = 60 * 60;
        long daySeconds = hourSeconds * 24;

        //天
        long days = seconds / daySeconds;
        if (days > 0) {
            builder.append(days).append("${day}");
        }
        //时
        long hours = seconds % daySeconds / hourSeconds;
        if (hours > 0) {
            builder.append(hours).append("${hour}");
        }

        //分
        long minus = seconds % daySeconds% hourSeconds / 60;
        if (minus > 0) {
            builder.append(minus).append("${minute}");
        }

        //秒
        long resultSeconds = seconds % daySeconds % hourSeconds % 60;
        if (resultSeconds > 0) {
            builder.append(resultSeconds).append("${second}");
        }

        return builder.toString();
    }

    /**
     * 原时区转目标时区
     * @param sourceTime
     * @param format
     * @param sourceTimeZone
     * @param targetTimeZone
     * @return
     */
    public static Date sourceTimeZoneToTargetTimeZone(String sourceTime, String format, TimeZone sourceTimeZone, TimeZone targetTimeZone){
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setTimeZone(sourceTimeZone);
        Date utcDate = null;
        try {
            utcDate = sdf.parse(sourceTime);
        } catch (ParseException e) {
            logger.error("ERROR:", e);
        }
        sdf.setTimeZone(targetTimeZone);
        Date locatlDate = null;
        String localTime = sdf.format(utcDate.getTime());
        try {
            locatlDate = sdf.parse(localTime);
        } catch (ParseException e) {
            logger.error("ERROR:", e);
        }
        return locatlDate;
    }

    /**
     * 将浏览器时区转java时区，默认取上下文时区
     * @param sourceTime
     * @return
     */
    public static String sourceTimeZoneToTargetTimeZone(String sourceTime){
        if (sourceTime.matches(timeFormat)) {
            TimeZone timeZone;
            if (StringUtils.isNotBlank(UserContentHolder.getTimeZone())) {
                timeZone = TimeZone.getTimeZone(UserContentHolder.getTimeZone());
            }else {
                timeZone = TimeZone.getDefault();
            }
            SimpleDateFormat sdf = new SimpleDateFormat(timePattern);
            sdf.setTimeZone(timeZone);
            Date utcDate = null;
            try {
                utcDate = sdf.parse(sourceTime);
            } catch (ParseException e) {
                logger.error("ERROR:", e);
            }
            sdf.setTimeZone(TimeZone.getDefault());
            return sdf.format(utcDate.getTime());
        }
        return sourceTime;
    }

    /**
     * 根据当前java机器时区转目标时区时间字符串
     * @param date
     * @param pattern
     * @param timezone
     * @return
     */
    public static String javaTimeToSourceTime(Date date, String pattern, TimeZone timezone){
        String output = StringUtils.EMPTY;
        if (null != date) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
            simpleDateFormat.setTimeZone(timezone);
            output = simpleDateFormat.format(date);
        }
        return output;
    }

    /**
     * 将字符串转date
     * @param time
     * @param pattern
     * @return
     */
    public static Date StringToDate(String time, String pattern){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        try {
            return simpleDateFormat.parse(time);
        } catch (ParseException e) {
            logger.error("ERROR:", e);
        }

        return null;
    }

    /**
     * 将date转字符串
     * @param time
     * @param pattern
     * @return
     */
    public static String DateToString(Date time, String pattern){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        return simpleDateFormat.format(time);
    }

    /**
     * 将时间戳转Date
     *
     * @param timeMillis
     * @return
     */
    public static Date timeMillisToDate(String timeMillis) {
        Long aLong = Long.valueOf(timeMillis);
        return new Date(aLong);
    }

    /**
     * 判断时间是否是2000-11-1 08:00:50
     * @param time
     * @return
     */
    public static boolean checkTimeFormat(String time) {
        if (time.matches(timeFormat)) {
            return true;
        }
        return false;
    }

}
